<?php

namespace app\service\audioVideo;

use app\common\controller\Common;


class Base extends Common
{

    /**
     * 获取音视频token
     * @param $user
     * @param string $channel_id
     * @author tangfen
     */
    public function getToken($user, $channel_id)
    {
        $app_id = config('aly_config.app_id');
        $app_key = config('aly_config.app_key');

        $nonce = 'AK-' . uniqid();
//        $user_id = $this->CreateUserID($channel_id, $user);

        $timestamp = strtotime(date('Y-m-d H:i:s', strtotime('+2day')));

        $token = $this->CreateToken($app_id, $app_key, $channel_id, $user, $nonce, $timestamp);

        $username = $user . '?appid=' . $app_id . '&channel=' . $channel_id . '&nonce=' . $nonce . '&timestamp=' . $timestamp;

        return   [
            'AppID' => $app_id,
//                'UserID' => $user_id,
            'UserID' => $user,//用用户id
            'ChannelID' => $channel_id,
            'Nonce' => $nonce,
            'Timestamp' => $timestamp,
            'Token' => $token,
            'GSLB' => ["https://rgslb.rtc.aliyuncs.com"],
            'true' => array(
                'username' => $username,
                'password' => $token
            )
        ];
    }

    /*
 * 获取频道id生成不重复的随机数
*/
    function getChannelId()
    {
        static $seed = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
        $str = '';
        for ($i = 0; $i < 9; $i++) {
            $rand = rand(0, count($seed) - 1);
            $temp = $seed[$rand];
            $str .= $temp;
            unset($seed[$rand]);
            $seed = array_values($seed);
        }
        return '1' . $str;
    }


    /*
     *  生成随机字符串
     *   $length    字符串长度
     *   @author tangfen
     */
    function getString($length)
    {
        // 密码字符集，可任意添加你需要的字符
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            // 这里提供两种字符获取方式
            // 第一种是使用 substr 截取$chars中的任意一位字符；
            // 第二种是取字符数组 $chars 的任意元素
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
            //  $str .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        return $str;
    }

    public
    function CreateUserID($channel_id, $user)
    {
        $s = $channel_id . '/' . $user;
        $uid = hash('sha256', $s);
        return substr($uid, 0, 16);
    }


    public
    function CreateToken($app_id, $app_key, $channel_id, $user_id, $nonce, $timestamp)
    {
        $s = $app_id . $app_key . $channel_id . $user_id . $nonce . $timestamp;
        $token = hash('sha256', $s);
        return $token;
    }


}